<template>
  <div>
    <div style="width: 100%;background: #fff">
      <el-input style="width: 590px"
                placeholder="输入关键字进行过滤"
                :clearable="true"
                v-model="treeProp.filterText" size="small">
      </el-input>
      <div class="treeStyleHeader">
        <i class="el-icon-menu"></i><span> 全部分类</span>
        <el-button icon="el-icon-plus" circle type="primary" size="mini"
                   @click="addCategory('allCategory')"></el-button>
      </div>
      <div class="tree">
        <v-tree :treeProp="treeProp"
                v-on:addCategory="addCategory"
                v-on:editCategory="editCategory"
                v-on:deleteCategory="deleteCategory"
                style="width: 600px;">
        </v-tree>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="40%">
      <div slot="title">
        {{dialogTitle}}
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" >
        <el-form-item label="商品品类名称" prop="name">
          <el-input v-model="ruleForm.categoryName" style="width:99%;"></el-input>
        </el-form-item>
        <el-form-item label="上级分类" prop="pid" v-if="action === 'add'">
          <el-select v-model="ruleForm.pid" placeholder="请选择" size="medium"  filterable allow-create clearable style="width:99%;">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="上级分类" prop="pid" v-else>
          <el-select v-model="ruleForm.pid" placeholder="请选择" size="medium"  filterable allow-create clearable style="width:99%;">
            <el-option :value="value">
              <el-tree  id="tree-option"
                        ref="selectTree"
                        :data="data"
                        :props="defaultProps"
                        @node-click="handleNodeClick"
                style="z-index:999999">
              </el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')" size="medium">提交</el-button>
          <el-button @click="resetForm('ruleForm')" size="medium">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
  import VSelect from "components/common/VSelect"
  import VTree from 'components/common/VTree'
  import VForm from 'components/common/VForm'
  import {localStorage} from 'js/localStorage'

  export default {
    inject: ['reload'],
    components: {
      VTree, VForm,VSelect
    },
    data() {
      return {
        //V-select-tree
        data:[],
        value:'',
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        //
        action: '',
        dialogVisible: false,
        dialogTitle: '',
        treeProp: {
          treeData: [],
          filterText: '',
          nodeKey: 'code',
          // icon: 'oms-icon icon-zidian,oms-icon icon-zidian1',
          showOperation: true,
          config: {
            defaultExpandedKeys: ['0'],
          }
        },
        showEditForm: false,
        ruleForm:{
          categoryName:'',
          pid:''
        },
        rules:{
          categoryName: [
            { required: true, message: '商品品类名称不能为空', trigger: 'change' }
          ],
          pid: [
            { required: true, message: '分类不能为空', trigger: 'change' }
          ]
        },
        dialogVisible: false,
        dialogTitle: '新增商品品类',
        options:[],
        id: '',
        pid:'',
        //el-select

      }
    },

    mounted() {
      this.initList()

    },
    methods: {
      //tree
      initList() {
        let succ = data => {
          if (data.statusCode === "1") {
            if(data.body !== null){
              data.body.forEach(ele => {
                var param = {
                  id: Number,
                  label: String,
                  children: []
                }
                param.id = ele.id
                param.label = ele.categoryName
                //二级
                if (ele.children) {
                  ele.children.forEach(item => {
                    if (item.pid === ele.id) {
                      var childA = {
                        id: Number,
                        label: String,
                        children: []
                      }
                      childA.id = item.id
                      childA.label = item.categoryName
                      param.children.push(childA)
                      //三级
                      if (item.children) {
                        item.children.forEach(child => {
                          if (child.pid === item.id) {
                            var childB = {
                              id: Number,
                              label: String,
                              children:[]
                            }
                            childB.id = child.id
                            childB.label = child.categoryName
                            // console.log(child.children,childB)
                            childA.children.push(childB)
                          }
                          //四级
                          if(child.children){
                            child.children.forEach(val=>{
                              if(val.pid ===child.id ){
                                var childC = {
                                  id: Number,
                                  label: String,
                                }
                                childC.id = val.id
                                childC.label = val.categoryName
                                childB.children.push(childC)
                              }
                            })
                          }
                        })
                      }
                    }
                  })
                }
                this.treeProp.treeData.push(param)
              })
            }
            //一级
          } else {
            this.$message.error(data.statusMessage)
          }
        }
        this.api.itemCategoryList({}, succ)
      },
      //添加
      addCategory(data, parentNode) {
        if(parentNode){
          if(parentNode.level === 4){
            this.$message.warning("不能在添加子集了")
            return  this.dialogVisible=false
          }
        }
        if(parentNode){
          this.id = parentNode.parent.data.id
        }
        //最上面的新增
        if (data === "allCategory") {
            let allCategory = [
              {label: '全部分类', id: 0, value: 0}
            ]
            this.options=allCategory
        }else{
          //父级（root）
          this.$nextTick(()=>{
            this.options=[];
            let root={
              label:data.label,
              value:data.id,
              id:data.id
            }
            let arr=[]
            arr.push(root)
            this.options=arr
            let  hash = {};
            this.options = this.options.reduce(function(item, next) {
              hash[next.name] ? '' : hash[next.name] = true && item.push(next);
              return item
            }, [])
          })
        }



        this.action = "add"
        this.dialogVisible = true
        this.dialogTitle = '新增商品品类'
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.operation()
          } else {
            return false;
          }
        });
      },
      operation(){
        if(this.action === "add"){
          this.add()
        }else{
          this.edit()
        }
      },
      //添加操作
      add() {
        let param=this.ruleForm
        param['userId'] = localStorage.get("userID")

        let succ = data => {
          if (data.statusCode === "1") {
            this.$message.success("新增成功")
            this.dialogVisible=false
            this.reload()
          } else {
            this.$message.error(data.statusMessage)
          }
        }
        this.api.itemCategoryAdd(param, succ)
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //编辑
      editCategory(data, parentNode) {
        this.data=this.treeProp.treeData
        // this.$refs.selectTree.setCurrentKey(data.id)
        this.ruleForm.categoryName = data.label
        this.id=data.id
        this.options.push(parentNode.parent.data)

        this.action = "edit"
        this.dialogVisible = true
        this.dialogTitle = '编辑商品品类信息'
      },
      //删除
      deleteCategory(data, node) {

        if (node.childNodes.length > 0) {
          return this.tips.ConfirmModal('请先删除子菜单后再删除当前菜单！');
        }
        this.tips.ConfirmModal('确认要删除这一个 【' + data.label + '】品类吗？', () => {
          let para = {
            id: data.id
          }
          let succ = data => {
            if (data.statusCode === "1") {
              this.$message.success("删除成功")
              this.reload()
            } else {
              this.$message.error(data.statusMessage)
            }
          }
          this.api.itemCategoryDelete(para, succ)
        });
      },
      handleReset(formName) {
        this.$refs.form.resetForm(formName);
      },
      edit(){
         let param=this.ruleForm
          param['id']=this.id
          param['userId'] = localStorage.get("userID")
          param.pid=this.pid
          let succ = data => {
            if (data.statusCode === "1") {
              this.$message.success("修改成功")
              this.dialogVisible=false
              this.reload()
            } else {
              this.$message.error(data.statusMessage)
            }
          }
        this.api.itemCategoryUpdate(param, succ)
      },
      handleNodeClick(data){
        this.ruleForm.pid=data.label
        this.pid=data.id

      }
    }
  }
</script>
<style>
  .el-select-dropdown__item.hover, .el-select-dropdown__item:hover{
    height:auto;
  }
  .el-select-dropdown__item{
    /*padding:0 !important*/
  }
</style>
<style scoped lang="scss">
  .treeStyleHeader {
    background: #fff;
    line-height: 50px;

    i {
      color: #409EFF;
      font-size: 20px;
      padding: 0 10px;
    }

    .el-button--mini.is-circle {
      padding: 5px !important;
    }

    span {
      color: #409EFF;
      display: inline-block;
    }

    .el-button {
      margin-left: 50px;
    }

  }

  .el-dialog {
    position: absolute;
    margin: 0 auto 50px;
    border-radius: 2px;
    -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
    box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
    -webkit-box-sizing: border-box;
    /* box-sizing: border-box; */
    width: 50%;
    top: 10%;
  }

  .el-input {
    margin-top: 10px;
    margin-left: 8px;
  }

</style>
